package com.glwan.fixedassetapp.ui.home.Activity;


import android.app.Activity;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;

import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;

import com.glwan.fixedassetapp.Adapter.ListableAdapter;
import com.glwan.fixedassetapp.R;
import com.glwan.fixedassetapp.components.SelectView;
import com.glwan.fixedassetapp.model.Asset;
import com.glwan.fixedassetapp.model.AssetOld;
import com.glwan.fixedassetapp.model.kingdee.KingDeeRepoRet;
import com.glwan.fixedassetapp.utils.CommonUtil;
import com.glwan.fixedassetapp.utils.KingDeeUtil;
import com.google.gson.Gson;

import org.apache.commons.lang.StringUtils;

import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

//盘点任务
public class InventoryTaskActivity extends AppCompatActivity {


    private static final String TAG = "InventoryTaskActivity";

    IntentFilter mScanResultIntentFilter;
    private List<Map<String, Object>> parentList = new ArrayList<>();

    private Map<String, Integer> groupTextViewMap = new HashMap<>();

    private ListView listView;

    private ListableAdapter listableAdapter;
    List<String> spinnerValueList = new ArrayList<>();
    List<AssetOld> addressList = new ArrayList<>();
    private SelectView selectView;


    List<Map<String, Object>> scannedList = new ArrayList<>();

    private Activity getActivity() {
        return this;
    }

    List<KingDeeRepoRet.InventScheme> inventSchemeList;

    Map<String, String> inventShcemeMap = new HashMap<>();

    private ExecutorService executorService = Executors.newSingleThreadExecutor();
    private Handler mainHandler = new Handler(Looper.getMainLooper());

    Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(@NonNull Message message) {
            if (message.what == 1) {
                initData();
            }
            if (message.what == 2) {
                initAddressData();
            }
            return true;
        }
    });


    private BroadcastReceiver scanResultReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String resultString = intent.getStringExtra("string");
            Log.d(TAG, "接收到扫码结果string:" + resultString);
            for (Map<String, Object> map : parentList) {
                if (resultString.replace("\r", "").replace("\t", "").replace("\n", "").equals(map.get("fAssetNo").toString())) {
                    if (null == map.get("initCheckId") || Integer.valueOf(map.get("initCheckId").toString()) == 0) {
                        map.put("fdSerialnumber", map.get("fAssetNo"));
                        Integer fQuantity = 0;
                        Integer initQty = 1;

                        if (null != map.get("fQuantity")) {
                            fQuantity = new BigDecimal(map.get("fQuantity").toString()).setScale(0).intValue();
                        }
                        if (fQuantity - initQty > 0) {
                            map.put("fdStatus", "盘亏");
                        }
                        if (fQuantity - initQty == 0) {
                            map.put("fdStatus", "已盘点");
                        }
                        if (fQuantity - initQty < 0) {
                            map.put("fdStatus", "盘亏");
                        }
                        map.put("initQty", initQty);
                    }
                }
                Log.i(TAG, "onReceive: " + new Gson().toJson(parentList));
                //更新数据
                Message message = handler.obtainMessage();
                message.what = 1;
                handler.sendMessage(message);

            }
        }
    };



    private Button btScanning;
    private Button uploadBtn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.fragment_home_inventory_task);
        registerScanResultReceiver();

        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        setTitle(getString(R.string.inventoryTask));
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setHomeButtonEnabled(true);
            actionBar.setDisplayHomeAsUpEnabled(true);
        }

        uploadBtn = findViewById(R.id.btUpload);
        uploadBtn.setOnClickListener(view -> {
            uploadData();
        });

        btScanning = findViewById(R.id.btScanning);
        btScanning.setOnClickListener(view -> {
            inventory();
        });

//        getAddressList();
        getInventScheme();
    }

    //弹框显示盘点方案
    private void showInventShcemeDialog() {
        CommonUtil.cancelProgressDialog(getActivity());
        String[] valuesArray = inventShcemeMap.values().toArray(new String[0]);
        new AlertDialog.Builder(this)
                .setTitle("选择盘点方案")
                .setItems(valuesArray, (dialog, which) -> {
                    if (dialog != null) {
                        dialog.dismiss();
                    }
                    handleSelection(which);
                }).create().show();
    }

    //选中方案选项
    private void handleSelection(int which) {
        String[] keysArray = inventShcemeMap.keySet().toArray(new String[0]);
        String number = keysArray[which];
        getDataNew(number);
    }

    //返回主界面
    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finish();
        }
        return super.onOptionsItemSelected(item);
    }

    //异步获取盘点方案
    private void getInventScheme() {
        executorService.execute(() -> {
            CommonUtil.openProgressDialog(getActivity(), getString(R.string.loading));
            // 执行网络请求
            inventSchemeList = KingDeeUtil.getInventSchemeNew();
            for (KingDeeRepoRet.InventScheme inventScheme : inventSchemeList) {
                inventShcemeMap.put(inventScheme.getInvent().getFID(), inventScheme.getFName());
            }
            CommonUtil.cancelProgressDialog(getActivity());
            // 在主线程中显示弹框
            mainHandler.post(() -> showInventShcemeDialog());
        });
    }

    /**
     * 获取数据
     */
    private void getDataNew(String number) {
        //打开加载框
        CommonUtil.openProgressDialog(getActivity(), getString(R.string.loading));
        // 启动子线程执行任务
        new Thread(new Runnable() {
            @Override
            public void run() {
                // 执行后台操作
                List<Asset> assetList = KingDeeUtil.getProductListData(number);
                List<Map<String, Object>> list = new ArrayList<>();

                Long sortNo = 0L;
                if (!assetList.isEmpty()) {
                    for (Asset asset : assetList) {
                        Map<String, Object> map = new HashMap<>();
                        Class<?> objClass = asset.getClass();
                        // 获取对象的所有字段
                        Field[] fields = objClass.getDeclaredFields();
                        for (Field field : fields) {
                            field.setAccessible(true); // 设置访问权限，确保可以读取私有字段
                            try {
                                String fieldName = field.getName();
                                Object fieldValue = field.get(asset);
                                // 将字段名称和值放入 Map 中
                                map.put(fieldName, fieldValue);
                            } catch (IllegalAccessException e) {
                                e.printStackTrace(); // 处理异常
                            }
                        }

                        sortNo++;
                        map.put("sortNo", sortNo);
                        if (null != asset.getProfitStatus() && StringUtils.isNotBlank(asset.getInitCheckerId())
                                && !"0".equals(asset.getInitCheckerId())) {
                            Long profitStatus = asset.getProfitStatus();
                            if (profitStatus == 1) {
                                map.put("fdStatus", "盘盈");
                            } else if (profitStatus == 2) {
                                map.put("fdStatus", "盘亏");
                            } else {
                                map.put("fdStatus", "已盘点");
                            }

                        }
                        map.put("fdSerialnumber", "");
                        map.put("fAssetNo", asset.getfAssetNO());
                        map.put("fdName", asset.getfName());
                        list.add(map);
                    }
                }
                parentList.addAll(list);
                Message message = handler.obtainMessage();
                message.what = 1;
                handler.sendMessage(message);
                CommonUtil.cancelProgressDialog(getActivity());
            }
        }).start();
    }

    private void initData() {
        groupTextViewMap.put("sortNo", R.id.sortNo);
        groupTextViewMap.put("fdName", R.id.fdYzCardName);
        groupTextViewMap.put("fdSerialnumber", R.id.fdId);
        groupTextViewMap.put("fdStatus", R.id.status);
        listView = findViewById(R.id.inventoryTaskList);
        listableAdapter = new ListableAdapter(getActivity(), parentList, groupTextViewMap, R.layout.offline_inventory_item);
        listView.setAdapter(listableAdapter);
        if (!parentList.isEmpty()) {
            //已盘点
            if (parentList.get(0).get("fDocumentStatus").equals("C")) {
                btScanning.setVisibility(View.GONE);
                uploadBtn.setVisibility(View.GONE);
                CommonUtil.openAlertDialog(InventoryTaskActivity.this, "提示", "此方案已盘点", 0);
            }else{
                btScanning.setVisibility(View.VISIBLE);
                uploadBtn.setVisibility(View.VISIBLE);
            }
        }
    }

    private void initAddressData() {
        selectView = findViewById(R.id.selectView);
        selectView.setAdapter(new ArrayAdapter<>(getActivity(), R.layout.support_simple_spinner_dropdown_item, spinnerValueList));
    }


    /**
     * 获取数据
     */
    private void getAddressList() {
        //打开加载框
        executorService.execute(() -> {
            // 执行网络请求
            Map<String, String> assetPosition = KingDeeUtil.getAssetPosition();
            if (!assetPosition.isEmpty()) {
                Collection<String> values = assetPosition.values();
                spinnerValueList = new ArrayList<>(values);
            }
            Message message = handler.obtainMessage();
            message.what = 2;
            handler.sendMessage(message);
        });
    }


    private void registerScanResultReceiver() {
        //注册接收扫码结果的广播
        mScanResultIntentFilter = new IntentFilter("com.uc.scanner.result"); //"com.uc.scanner.result"这个action值 对应 "扫描助手App"广播模式的广播action
        registerReceiver(scanResultReceiver, mScanResultIntentFilter);
    }

    private void inventory() {
        if (getString(R.string.startScanning).equals(btScanning.getText().toString())) {
            btScanning.setText(getString(R.string.stopScanning));
            Intent intent = new Intent("com.uc.scanner.trigger.START");//"com.uc.scanner.trigger.START"这个action值 对应 "扫描助手App"设置启动广播的action
            sendBroadcast(intent);
        } else {
            btScanning.setText(getString(R.string.startScanning));
            Intent intent = new Intent("com.uc.scanner.trigger.STOP");//"com.uc.scanner.trigger.STOP"这个action值 对应 "扫描助手App"设置启动广播的action
            sendBroadcast(intent);
        }
    }

    private void uploadData() {
        CommonUtil.openProgressDialog(getActivity(), getString(R.string.loading));
        executorService.execute(() -> {
            Boolean result = KingDeeUtil.uploadData(parentList);
            CommonUtil.cancelProgressDialog(getActivity());
            if (result) {
                CommonUtil.toastShow(getActivity(), "提交成功", 0, false);
            } else {
                CommonUtil.toastShow(getActivity(), "提示失败", 0, false);
            }
        });
    }

    private void reportScannedList() {
        parentList.addAll(scannedList);
        scannedList.clear();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (scanResultReceiver != null) {
            unregisterReceiver(scanResultReceiver);
        }

    }
}


